package org.jeecg.modules.wei.controller.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.wei.entity.WeiArticle;
import org.jeecg.modules.wei.service.IWeiArticleService;
import org.jeecg.modules.wei.service.IWeiCommentService;
import org.jeecg.modules.wei.service.IWeiCountDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Calendar;
import java.util.Date;

/**
 * 头条文章列表
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/api/toutiao/")
@Slf4j
public class TouTiaoFrontController {
	
	@Autowired
	private IWeiArticleService weiArticleService;
	@Autowired
	private IWeiCommentService weiCommentService;
	
	@Autowired
	private IWeiCountDataService weiCountDataService;

	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;

	/**
	 * http://localhost:8080/jeecg-boot/api/toutiao/upload
	 */
	@PostMapping(value = "/upload")
	public Result upload(HttpServletRequest request, HttpServletResponse response) {
		Result result = new Result<>();
		String uid = "50097074575";
		String createby = "平安邯郸";  //今日头条
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
			String text = readJsonFile(mf.getInputStream());
			System.out.println(text);

			JSONObject json = JSON.parseObject(text);

			System.out.println(json.toString());

			if(json.getBoolean("has_more")) {
				JSONArray arr = json.getJSONArray("data");
				if(arr != null && arr.size() > 0) {
					for(int i = 0; i < arr.size(); i++) {
						JSONObject timeline = arr.getJSONObject(i);
						System.out.println("阅读:" + timeline.getIntValue("go_detail_count"));
						System.out.println("评论:" + timeline.getIntValue("comments_count"));
						System.out.println(timeline.getString("title"));
						System.out.println(timeline.getString("item_id"));
						System.out.println(timeline.getString("behot_time"));
						System.out.println("https://www.toutiao.com/i"+timeline.getString("item_id"));

						WeiArticle info = new WeiArticle();
						info.setTitle(timeline.getString("title"));
						info.setId(timeline.getString("item_id"));
						info.setMsgid(timeline.getString("item_id"));
						info.setType(3);		//头条
						info.setUid(uid);
						info.setUrl(timeline.getString("url"));
						info.setCreateBy(createby);
						info.setShareCount(timeline.getIntValue("comments_count"));
						info.setClickCount(timeline.getIntValue("go_detail_count"));
						info.setUrl("https://www.toutiao.com/i"+info.getId()+"/");

//						String publishDate = DateUtils.timestampToString(timeline.getIntValue("publishDate"));
//						info.setCreateTime(DateUtils.str2Date(publishDate, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
						try {
							String time = timeline.getString("behot_time");
							if(time.contains("天内")){
								time = time.replace("天内","");
								info.setCreateTime(getDateBefore(new Date(), 1));
							}else if(time.contains("周内")){
								time = time.replace("周内","");
								info.setCreateTime(getDateBefore(new Date(), 7));
							}else if(time.contains("天前")){
								time = time.replace("天前","");
								info.setCreateTime(getDateBefore(new Date(), Integer.parseInt(time)));
							}else if(time.contains("月前")){
								time = time.replace("月前","");
								info.setCreateTime(getDateBefore(new Date(), 30));
							}
							info.setCommentCount(timeline.getIntValue("comments_count"));
							weiArticleService.saveOrUpdate(info);

						} catch (Exception e) {
							e.printStackTrace();
						}
						System.out.println("-----------------------------------------------------------");
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	//读取json文件
	public String readJsonFile(InputStream inputStream) {
		String jsonStr = "";
		try {
			Reader reader = new InputStreamReader(inputStream,"utf-8");
			int ch = 0;
			StringBuffer sb = new StringBuffer();
			while ((ch = reader.read()) != -1) {
				sb.append((char) ch);
			}
			reader.close();
			jsonStr = sb.toString();
			return jsonStr;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public Date getDateBefore(Date d, int day) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		return now.getTime();

	}

}
